// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database();
// 云函数入口函数
exports.main = async (event, context) => {
  try {
    const wxContext = cloud.getWXContext()
    //通过JS的方法获取当前年月日
    var date = new Date();
    date = new Date(date.getTime() + 8 * 60 * 60 * 1000);
    //获取年份  
    const Y = date.getFullYear();
    //获取月份  
    const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    //获取当日日期 
    const D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    const total = await db.collection('reviewDays').where({
      user_id: wxContext.OPENID,
      time: {
        year: Y,
        month: M,
        day: D,
      }
    }).count();
    if (total.total == 0) {
      await db.collection('reviewDays').add({
        data: {
          user_id: wxContext.OPENID,
          time: {
            year: Y,
            month: M,
            day: D
          }
        }
      })
      return {
        msg: "添加完成",
      }
    } else
      return {
        msg: "已添加",
      }
  } catch (e) {
    console.error(e);
  }
}